package com.fs.util;

import com.fs.util.baiduutils.Base64Util;
import com.fs.util.baiduutils.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URLEncoder;

@Component
public class Seal {
    private String uploadPath="C:/uploads/images";

    public static final String SEAL_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/seal";
    public static final String QR_CODE_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode";

    public String seal(String imageName, String way) {
        try {
            // 从外部目录读取文件
            File file = new File(uploadPath + File.separator + imageName);
            InputStream resourceStream = new FileInputStream(file);
            if (resourceStream == null) {
                throw new FileNotFoundException("File not found: " + imageName);
            }
            // 将 InputStream 转换为 byte[]
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int bytesRead;
            byte[] data = new byte[1024];
            while ((bytesRead = resourceStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, bytesRead);
            }
            byte[] imgData = buffer.toByteArray();

            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间，客户端可自行缓存，过期后重新获取。
            String accessToken = "24.e268182d39be87aafd2c0d7533612f77.2592000.1721440161.282335-82351579";

            String result = null;
            if ("seal".equals(way)) {
                result = HttpUtil.post(SEAL_URL, accessToken, param);
            } else if ("qrcode".equals(way)) {
                result = HttpUtil.post(QR_CODE_URL, accessToken, param);
            }
            System.out.println("----------------------------------------------" + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        // 传递图片文件名
        Seal seal = new Seal();
        seal.seal("{906B898D-1C7E-1898-3FAB-31EACDA474EA}.jpg", "seal");
    }
}
